package cn.tedu.csmall.product.service.impl;

import cn.tedu.csmall.product.service.IAdminService;
import cn.tedu.csmall.product.ex.ServiceException;
import cn.tedu.csmall.product.mapper.AdminMapper;
import cn.tedu.csmall.product.pojo.dto.AdminDTO;
import cn.tedu.csmall.product.pojo.entity.Admin;
import cn.tedu.csmall.product.web.ServiceCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class AdminServiceImpl implements IAdminService {
    @Autowired
    private AdminMapper adminMapper;
    @Override
    public void addNew(AdminDTO adminDTO) {
        String username = adminDTO.getUsername();
        String phone = adminDTO.getPhone();
        String email = adminDTO.getEmail();
        int countByUsername = adminMapper.countByUsername(username);
        if(countByUsername>0){
            String message = "添加管理员失败，用户名已存在";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT,message);
        }
        int countByPhone = adminMapper.countByPhone(phone);
        if(countByPhone>0){
            String message = "添加管理员失败，手机号已存在";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT,message);
        }
        int countByEmail = adminMapper.countByEmail(email);
        if(countByEmail>0){
            String message = "添加管理员失败，电子邮箱已存在";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT,message);
        }
        Admin admin = new Admin();
        BeanUtils.copyProperties(adminDTO,admin);
        adminMapper.insert(admin);
    }
}
